﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
using Windows.Data.Json;

namespace GComp.Apps.EasyStock.DataModel.Common {
    /// <summary>
    /// Yahoo Query Language; siehe http://developer.yahoo.com/yql/
    /// </summary>
    public class YQLQuery {
        const string UrlTemplate = "http://query.yahooapis.com/v1/public/yql?q={0}&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys";
        protected string _query;

        protected YQLQuery() {
        }

        public YQLQuery(string query) {
            _query = query;

            //select * from yahoo.finance.historicaldata where symbol = "MSFT" and startDate = "2012-08-19" and endDate = "2012-09-18"
            //select * from yahoo.finance.historicaldata where symbol = "MSFT" and startDate = "2012-08-19" and endDate = "2012-09-18"
        }

        public async Task<XDocument> GetXmlAnswerAsync() {
            Uri url = new Uri(string.Format(UrlTemplate, Uri.EscapeUriString(_query)));
            var client = new HttpClient();
            using (var resp = await client.GetAsync(url)) {
                string xml = await resp.Content.ReadAsStringAsync();
                return XDocument.Parse(xml);
            }
        }

        public async Task<JsonValue> GetJsonAnswerAsync() {
            var frm = string.Format(UrlTemplate, Uri.EscapeUriString(_query));
            Uri url = new Uri(frm + "&format=json");
            var client = new HttpClient();
            using (var resp = await client.GetAsync(url)) {
                string json = await resp.Content.ReadAsStringAsync();
                return JsonValue.Parse(json);
            }
        }
    }
}
